package com.takeoutOrder.server.service.impl;

import java.util.List;
import com.takeoutOrder.common.utils.DateUtils;
import com.takeoutOrder.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.takeoutOrder.server.mapper.ShoppingCartMapper;
import com.takeoutOrder.server.domain.ShoppingCart;
import com.takeoutOrder.server.service.IShoppingCartService;

/**
 * 购物车Service业务层处理
 * 
 * @author linzechen
 * @date 2024-11-30
 */
@Service
public class ShoppingCartServiceImpl implements IShoppingCartService 
{
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 查询购物车
     * 
     * @param id 购物车主键
     * @return 购物车
     */
    @Override
    public ShoppingCart selectShoppingCartById(Long id)
    {
        return shoppingCartMapper.selectShoppingCartById(id);
    }

    /**
     * 查询购物车列表
     * 
     * @param shoppingCart 购物车
     * @return 购物车
     */
    @Override
    public List<ShoppingCart> selectShoppingCartList(ShoppingCart shoppingCart)
    {
        return shoppingCartMapper.selectShoppingCartList(shoppingCart);
    }

    /**
     * 新增购物车
     * 
     * @param shoppingCart 购物车
     * @return 结果
     */
    @Override
    public int insertShoppingCart(List<ShoppingCart> shoppingCart)
    {

        //判断是否为本人操作,如果不是返回错误
        Long userId = SecurityUtils.getUserId();
        for (ShoppingCart cart : shoppingCart) {
            if (!cart.getUserId().equals(userId)){
                throw new RuntimeException("只能修改本人的购物车!");
            }
        }
        if (shoppingCart.isEmpty()){
            shoppingCartMapper.deleteShoppingCartByUserId(userId);
            return 0;
        }
        shoppingCartMapper.deleteShoppingCartByUserId(userId);
        shoppingCart.stream().forEach(cart -> cart.setCreateTime(DateUtils.getNowDate()));
        return shoppingCartMapper.insertShoppingCart(shoppingCart);
    }

    /**
     * 修改购物车
     * 
     * @param shoppingCart 购物车
     * @return 结果
     */
    @Override
    public int updateShoppingCart(ShoppingCart shoppingCart)
    {
        return shoppingCartMapper.updateShoppingCart(shoppingCart);
    }

    /**
     * 批量删除购物车
     * 
     * @param ids 需要删除的购物车主键
     * @return 结果
     */
    @Override
    public int deleteShoppingCartByIds(Long[] ids)
    {
        return shoppingCartMapper.deleteShoppingCartByIds(ids);
    }

    /**
     * 删除购物车信息
     * 
     * @param id 购物车主键
     * @return 结果
     */
    @Override
    public int deleteShoppingCartById(Long id)
    {
        return shoppingCartMapper.deleteShoppingCartById(id);
    }
}
